package com.hxk.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

/**
 * spring文件上传下载
 * @author Cactus
 */
@Controller
public class FileDUController {

	@RequestMapping("download")
	public void download(String fileName, HttpServletResponse resp, HttpServletRequest req) throws IOException{
		//设置响应流中文件进行下载
		resp.setHeader("Content-Disposition", "attachment;filename="+fileName);
		//获取相应输出字节流
		ServletOutputStream os = resp.getOutputStream();
		//获取服务器文件路径
		String filePath = req.getServletContext().getRealPath("files");
		//创建文件类
		File file = new File(filePath, fileName);
		//将文件读成二进制数组
		byte[] bytes = FileUtils.readFileToByteArray(file);
		//将读到的二进制数组写入到响应流中
		os.write(bytes);
		os.flush();
		os.close();
	}
	
	@RequestMapping("upload")
	public String upload(MultipartFile file) throws IOException{
		//获取上传文件的真实名称
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		String tempFileName = UUID.randomUUID().toString();
		File tfile = new File("e:/"+tempFileName+suffix);
		FileUtils.copyInputStreamToFile(file.getInputStream(), tfile);
		return "index";
	}
}
